package trancation;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:mysql/spring-config.xml")
@TransactionConfiguration(transactionManager = "txManager")

public class RollBackTest {
	@Autowired
	private DataSource ds;

	@Test

	public void testRollBackInException2() throws Exception {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
		oper(jdbcTemplate);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void oper(JdbcTemplate jdbcTemplate) throws Exception {

		updateUser(jdbcTemplate);

		queryRes(jdbcTemplate);
	}

	@Transactional
	private void insertUser(JdbcTemplate jdbcTemplate) {
		String sql = "insert into user values (?,?)";

		jdbcTemplate.update(sql, "li", 13);
	}

	@Transactional
	private void updateUser(JdbcTemplate jdbcTemplate) throws Exception {

		insertUser(jdbcTemplate);
		String a = null;

		if (a.equals("")) {
			System.out.println("ok");
		} else {
			throw new RuntimeException();
		}
		jdbcTemplate.update("update user set name='v' where age =4");

	}

	private void queryRes(JdbcTemplate jdbcTemplate) {
		jdbcTemplate.query("select * from user", new RowCallbackHandler() {

			@Override
			public void processRow(ResultSet rs) throws SQLException {
				String name = rs.getString(1);
				int age = rs.getInt(2);
				System.out.println(name + "-" + age);

			}

		});
	}

}
